package com.jy.wms.common.realm;

import com.jy.wms.dao.LoginMapper;
import com.jy.wms.pojo.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName: MyRealm
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author zzp
 * @Date 2017/7/28 9:37
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    LoginMapper loginMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;//当前用户登录传过来的
        String username = token.getUsername();//获取前端传过来的username
        SysUser user=loginMapper.getUserInfo(username);//数据库的
        if(user!=null){
            Subject sub= SecurityUtils.getSubject();
            //sub.getSession().setAttribute(SessionInfo.SessionDB,user.getSjk());
            //判断是否为主库
            SimpleAuthenticationInfo info=null;
            //ByteSource.Util.bytes(user.getSalt())这里面放入的salt是前台输入了以后用这个salt加密和下面传入的password（数据库中的）做对比
            return new SimpleAuthenticationInfo(user.getDlm(),user.getMm(),ByteSource.Util.bytes(user.getYz()),this.getName());//通过这个方法把用户传过来的和数据库做对比
        }else{
            throw new UnknownAccountException();
        }
    }
    private static String generateSalt(){
        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
        String hex = secureRandom.nextBytes(3).toHex(); //一个Byte占两个字节，此处生成的3字节，字符串长度为6
        SimpleHash sh=new SimpleHash("MD5","123456",ByteSource.Util.bytes("91f10c"),1024);
        System.out.println(sh);
        System.out.println(hex);
        return hex;
    }

    public static void main(String[] args) {
        MyRealm.generateSalt();
    }
}
